import { config } from '@e/config';
import { selectMdFileDialog } from '@e/dialog/selectFile';
import { createWindow, batchCreateWindow } from '@e/createWindow';
import { BrowserWindow, MenuItem, MenuItemConstructorOptions, KeyboardEvent } from 'electron';

/**
 * 打开新文件
 */
function openNewFile(_menuItem: MenuItem, browserWindow: BrowserWindow | undefined, _event: KeyboardEvent): void {
	const paths = selectMdFileDialog(browserWindow, void 0, void 0, true);

	if (paths) batchCreateWindow(paths);
}

let loading = false;

/**
 * 新建窗口
 */
function newWindow() {
	// 必须在上一个窗口创建完毕，才能创建下一个窗口
	if (!loading) {
		loading = true;
		const { service } = createWindow();
		service.on('load', () => (loading = false));
	}
}

const template: MenuItemConstructorOptions[] = [
	{
		label: 'Edit',
		submenu: [
			{ label: '全屏', role: 'togglefullscreen', accelerator: 'F11' },
			{ label: '打开新文件', accelerator: 'Ctrl+O', click: openNewFile },
			{ label: '新建窗口', accelerator: 'Ctrl+N', click: newWindow },
		],
	},
];

if (config.isDevEnv()) {
	(template[0].submenu as MenuItemConstructorOptions[]).push(
		{ label: '刷新', role: 'reload', accelerator: 'F5' },
		{ label: '开发者工具', role: 'toggleDevTools', accelerator: 'F12' }
	);
} else {
	(template[0].submenu as MenuItemConstructorOptions[]).push(
		{ label: '刷新', role: 'reload', accelerator: 'Alt+F5' },
		{ label: '开发者工具', role: 'toggleDevTools', accelerator: 'Alt+F12' }
	);
}

export const menuTemplate = template;
